<?php
class UsersController extends AppController {
	public $name = 'Users';
	public $components = array('Session', 'Security', 'Auth');


	public function index(){
		$this->set("users", $this->User->find('all'));
	}

	public function login(){
		$this->layout = 'login';
		if($this->Auth->login()){
			$roleData = $this->User->Role->find('all', array(
				'conditions' => array('id' => $this->Auth->user('role_id')),
			));
			$this->Session->write('Auth.User.Role', $roleData['0']['Role']);

			$this->redirect($this->Auth->redirect());
		}
	}

	public function logout(){
		$this->redirect($this->Auth->logout());
	}

	public function add(){
		$this->loadModel('Role');
		$this->set("roles", $this->Role->find('list'));
		if($this->request->is("post")){
			$this->User->create();
			if($this->User->saveAssociated($this->request->data)){
				$this->Session->setFlash("User created", "default", array("class" => "success"));
				$this->redirect(array("action" => "index"));
			}
		}
	}

	public function edit($id = null){
		$this->User->id = $id;
		if(!$this->User->exists()){
			throw new NotFoundException('Invalid user');
		}

		$this->loadModel('Role');
		$selectedRoles = null;
		$this->set(array(
			"roles" => $this->Role->find('list'),
			"selectedRoles" => $selectedRoles
		));
		if($this->request->is("get")){

			$this->request->data = $this->User->read();
			unset($this->request->data['User']['password']);
		}else{
			if($this->User->saveAssociated($this->request->data)){
				$this->Session->setFlash("User updated", "default", array("class"=> "success"));
				$this->redirect(array("action" => "index"));
			}
		}
	}

	public function delete(){
		if($this->request->is("get")){
			throw new MethodNotAllowedException();
		}
		if(count($this->request->data['User']['selectedUsers']) < 1){
			$this->redirect(array("action" => "index"));
		}
		$i = 0;
		foreach($this->request->data['User']['selectedUsers'] as $userid){
			if(AuthComponent::user('id') !== $userid){
				// can't delete currently loggedin user

				$this->User->id = $userid;
				if($this->User->delete()){
					$i++;
				}
			}
		}
		$this->Session->setFlash($i . ": Users have been deleted", "default", array("class" => "error-message"));
		$this->redirect(array("action"=> "index"));
	}
}